﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SweetSurvey.Models.Repositories
{
    public class AnswerRepository: IAnswerRepository
    {
        #region IRepository<Answer,string> Members

        public Answer Get(string id, bool detaching = true)
        {
            var context = new SweetSurveyModelContainer();
            var entity = context.Answers.Where(e => e.Id == id).Single();
            if (detaching) { context.Detach(entity); }
            return entity;
        }

        public string Create(Answer entity)
        {
            if (string.IsNullOrEmpty(entity.Id))
                entity.Id = RepositoryBase.GenerateRandomId();
            var context = new SweetSurveyModelContainer();
            context.Answers.AddObject(entity);
            context.SaveChanges();
            return entity.Id;
        }

        public void Update(Answer entity)
        {
            RepositoryBase.Update(entity);
        }

        public void Delete(string id)
        {
            RepositoryBase.Delete(Get(id));
        }

        #endregion

        #region IAnswerRepository Members

        public int GetAnswerCountByOptionId(string optionId)
        {
            var context = new SweetSurveyModelContainer();
            return (from a in context.Answers
                    where a.OptionId == optionId
                    select a).Count();
        }

        public IList<int> GetAnswerCountsByQuestionId(string questionId)
        {
            var optionRepository = new OptionRepository();
            var options = optionRepository.GetOptionsByQuestionId(questionId);
            var counts = new List<int>();
            foreach (var option in options)
            {
                counts.Add(GetAnswerCountByOptionId(option.Id));
            }
            return counts;
        }

        #endregion
    }
}